﻿// provides interop functionality
window.p2pRegister = function(plugin){
    window.p2pInterop = plugin.content.P2PInterop;
}
window.p2pNetworkAvailable = function(){
    return window.external != null && window.external.Channel != null;
}
window.p2pConnect = function(){
    window.external.Channel.Initialize();
}
window.p2pClose = function(){
    window.external.CloseApp();
}
window.p2pEnterIM = function(im){
    window.external.Channel.EnterIM(im);
}
window.p2pSendData = function(data){
    window.external.Channel.SendData(data);
}
window.p2pSendIM = function(im){
    window.external.Channel.SendIM(im);
}
window.p2pSendIMAsUser = function(im){
    window.external.Channel.SendIMAsUser(im);
}
window.Channel_OnAppClose = function(){
    window.p2pInterop.Channel_OnAppClose();
}
window.Channel_OnDataError = function(){
    var error = window.external.Channel.Error;
    var type = error.Type;
    var data = error.Data.toString();
    window.p2pInterop.Channel_OnDataError(type, data);
}
window.Channel_OnDataReceived = function(){
    var data = window.external.Channel.Data.toString();
    window.p2pInterop.Channel_OnDataReceived(data);
}
window.Channel_OnFileProgress = function(){
    // TODO: implement
}
window.Channel_OnFileReceived = function(){
    // TODO: implement
}
window.Channel_OnIMReceived = function(){
    var im = window.external.Channel.IM;
    window.external.Channel.IM = window.p2pInterop.Channel_OnIMReceived(im);
}
window.Channel_OnRemoteAppClosed = function(){
    window.p2pInterop.Channel_OnRemoteAppClosed();
}
window.Channel_OnRemoteAppLoaded = function(){
    var users = window.external.Users;
    for(var i = 0; i < users.Count; i++){
        var user = users.Item(i);

        var email = user.Email ? user.Email : "";
        var globalIp = user.GlobalIP ? user.GlobalIP : "";
        var localIp = user.LocalIP ? user.LocalIP : "";
        var name = user.Name ? user.Name : "";
        var puid = user.PUID ? "" + user.PUID : "";
        var isMe = (users.Me == user);
        var isInviter = (users.Inviter == user);
        
        window.p2pInterop.AddUser(email, globalIp, localIp, name, puid, isMe, isInviter);
    }

    window.p2pInterop.Channel_OnRemoteAppLoaded();
}
window.Channel_OnSendFileCancelled = function(){
    // TODO: implement
}
window.Channel_OnTypeChanged = function(){
    var type = window.external.Channel.Type;
    window.p2pInterop.Channel_OnTypeChanged(type);
}
